<?php


require_once("inc.member.php");





$this_title=__("SignUp Member");


$page_title=__("SignUp Member");


$content_title=__("SignUp Member");





$r_position=array(1,2);


$r_position_d=array(1=>__("Left"),2=>__("Right"));


$country_code=$vars['common']['country_code'];


array_shift($country_code);


$country_code_t=$vars['common']['country_code_text'];


foreach($country_code_t as $code=>$cname){


 $country_code_d[$code]=__($cname);


}


$r_payment_channel=array('eswallet','mwallet');

$r_payment_channel_d=array('eswallet'=>__($vars['eswallet_title'])." ".$vars['currency'].number_format($r_user['eswallet'], 2), 'mwallet'=>__($vars['mwallet_title'])." ".$vars['currency'].number_format($r_user['mwallet'], 2)." ".__("(Max 50%, balance will deduct from SP)"));

$r_package=$vars['r_package'];

$r_package_d=$vars['r_package_detail'];

$td_width=175;





require_once("inc.register_tab.php");





//#####AJAX CALL#####


if($_GET["aj"] && $_GET["check_ref"]){


	if(!$r_ref=@mysql_fetch_assoc(mysql_query("select * from $db->users where code='$post_d[ref]' and status in ('suspended','normal')"))){


		$ajerrmsg=replace_tag(__("Sponsor ID '<%id%>' could not be found."), array("<%id%>"=>$post_h['ref']));


	}else{


		$ajmsg=replace_tag(__("Sponsor ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$post_h['ref'], "<%name%>"=>$r_ref['username']));


	}


	$xml=array("status"=>($ajerrmsg? "2" : "1"), "msg"=>$ajmsg.$ajerrmsg);


	print format_xml($xml);


	exit();


}





if($_GET["aj"] && $_GET["check_upline"]){


	if(!$r_ref=@mysql_fetch_assoc(mysql_query("select * from $db->users where code='$post_d[ref]' and status in ('suspended','normal','n')"))){


		$ajerrmsg=replace_tag(__("Placement ID '<%id%>' could not be found."), array("<%id%>"=>$post_h['ref']));


	}else{


		$ajmsg=replace_tag(__("Placement ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$post_h['ref'], "<%name%>"=>$r_ref['username']));


	}


	$xml=array("status"=>($ajerrmsg? "2" : "1"), "msg"=>$ajmsg.$ajerrmsg);


	print format_xml($xml);


	exit();


}


//#####END AJAX CALL#####





//#####REGISTER POST#####


if($_SESSION["user_register"] && $_POST["__req"]){


	/*##### ERROR CHECK #####*/

	$chk_arr="_password,_password2,_email";


	$chk_arr2=$chk_arr;
	$chk_arr2=explode(",", $chk_arr2);
	$chk_arr=explode(",", $chk_arr);

	foreach($post_s as $f=>$v){


		if(in_array($f, $chk_arr2)){


			$data[$f]=$v;


		}


	}


	$errmsg=verify_form_data("users", $data);


	if(!$errmsg){


		//check referrer


		if($post_s["ref"]){


			if(!$r_ref=@mysql_fetch_assoc(mysql_query("select * from $db->users where code='$post_d[ref]' and status in ('suspended','normal')"))){


				$errmsg.=replace_tag(__("Sponsor ID: '<%rid%>' cannot be found in the database."), array("<%rid%>"=>$post_h['ref']))."<br />\n";


			}elseif($r_ref['activated'] != 'y'){


				$errmsg.=replace_tag(__("Sponsor ID: '<%rid%>' is not activated and cannot sponsor new member."), array("<%rid%>"=>$post_h['ref']))."<br />\n";


			}else{


				$ref_found=1;


				$ref_id=$r_ref["id"];


			}


		}else{


			$ref_id=0;


		}


		//check placement


		if($post_s["matrix_upline"]){


			if(!$r_upline=@mysql_fetch_assoc(mysql_query("select * from $db->users where code='$post_d[matrix_upline]' and status in ('suspended','normal','n')"))){


				$errmsg.=replace_tag(__("Placement ID: '<%rid%>' cannot be found in the database."), array("<%rid%>"=>$post_h['matrix_upline']))."<br />\n";


			}else{
				$matrix_upline_info=get_user_detail_by_code($post_d['matrix_upline']);

				if(!in_array($post_s['matrix_position'], $r_position)){


					$errmsg.=__("Please select a position.")."<br />";


				}elseif(@mysql_num_rows(mysql_query("select * from $db->users where matrix_upline='$matrix_upline_info[id]' and matrix_position='$post_d[matrix_position]'"))){


					$errmsg.=__("The selected Placement ID and position is already occupied.")."<br />";


				}else{
					
					$matrix_upline_id = $matrix_upline_info["id"];
					
				}


			}


		}else{


			$errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Placement ID")))."<br />";


		}


		if(!$errmsg){


			if($post_s['matrix_upline'] != $post_s['ref'] ){
				
				$sponsor = get_user_detail_by_code($post_s['ref']);
				$placement = get_user_detail_by_code($post_s['matrix_upline']);
				
				if(!is_group_matrix_downline_of($placement['id'], $sponsor['id'])){
					
					$errmsg.=__("The selected Placement ID is not in the network group of the Sponsor ID.")."<br />";	
					
				}

			}


		}


		if(!in_array($post_s['package'], $r_package)){


			$errmsg.=__("Please select product.")."<br />";


		}


		if(!in_array($post_s['payment_channel'], $r_payment_channel)){


			$errmsg.=__("Please select a payment channel.")."<br />";


		}else{
			
			$cost = $vars['package'][$post_s['package']]['price'];
			$bv = $vars['package'][$post_s['package']]['bv'];
			
			if($post_s['payment_channel'] == 'ewallet') $deduct_amount = $cost;
			else $deduct_amount = $bv;
			
			if($post_s['payment_channel'] == 'mwallet'){
				$deduct_amount;
				if($r_user['eswallet'] < $deduct_amount){
					if($r_user['mwallet'] >= ($deduct_amount/2)){
						if($r_user['eswallet'] < ($deduct_amount/2)){
							$errmsg.=replace_tag(__("You do not have sufficient <%title%> to activate this package."), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title'])))."<br />\n".replace_tag(__("<%title%> required: <%x%>"), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title']), "<%x%>"=>number_format($deduct_amount, 2)))."<br />\n".replace_tag(__("<%title%> available: <%x%>"), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title']), "<%x%>"=>number_format($r_user[$post_s['payment_channel']], 2)))."<br />\n";
						}
					}else{
						$bal = $deduct_amount - $r_user['mwallet'];
						if($r_user['eswallet'] < $bal){
							$errmsg.=replace_tag(__("You do not have sufficient <%title%> to activate this package."), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title'])))."<br />\n".replace_tag(__("<%title%> required: <%x%>"), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title']), "<%x%>"=>number_format($deduct_amount, 2)))."<br />\n".replace_tag(__("<%title%> available: <%x%>"), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title']), "<%x%>"=>number_format($r_user[$post_s['payment_channel']], 2)))."<br />\n";
						}
					}
				}
			}else{
				if($r_user[$post_s['payment_channel']] < $deduct_amount){
					$errmsg.=replace_tag(__("You do not have sufficient <%title%> to activate this package."), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title'])))."<br />\n".replace_tag(__("<%title%> required: <%x%>"), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title']), "<%x%>"=>number_format($deduct_amount, 2)))."<br />\n".replace_tag(__("<%title%> available: <%x%>"), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title']), "<%x%>"=>number_format($r_user[$post_s['payment_channel']], 2)))."<br />\n";
				}	
			}
		}


		//check email
		if(strlen($post_s['_email'])){

			if(!verify_email($post_s["_email"])){

				$errmsg.=__("Please provide a valid email address.")."<br />\n";

			//}elseif(email_found($post_s['_email'])){

			//	$errmsg.=replace_tag(__("The email address '<%email%>' is already in use, please providee another."), array("<%email%>"=>$post_s['_email']))."<br />\n";
		
			}

		}

	}

	//#####END ERROR CHECK#####





	$preview = $confirm = false;


	if(!$errmsg){


		if(!$post_s['__confirm'] && !$post_s['__edit']){


			$preview = true;


		}elseif($post_s['__confirm']){


			$confirm = true;


		}


	}





	//#####ADD TO DB#####

    //var_dump("exit1233333");
    //exit();
	if(!$errmsg && $confirm){


		$salt=generate_random_code(32);


		$enc_pass=md5($post_s["_password"].$salt).":".$salt;
		
		$ewallet_enc_password=md5($post_s["_password2"].$salt).":".$salt;


		$status='normal';


		$vc=generate_random_code(20);


		$rank_a = $vars['package'][$post_s['package']]['rank'];
		$total_account = $vars['package'][$post_s['package']]['account'];
		
		$datetime=ndate($vars["system_date_format"]);


		$dist_code = generate_code($post_d['country']);
		
		//if not pay then cannot use below code
		$sql="insert into $db->users (code, ref, creator, cid, rank_a, matrix_upline, matrix_position, email, username, password, ewallet_password, enc_password, ewallet_enc_password, country, status, activated, activated_date, cdate) values ('$dist_code', '$ref_id', 'u', '$uid', '$rank_a', '$matrix_upline_id', '$post_d[matrix_position]', '$post_d[_email]', '$dist_code', '$post_d[_password]', '$post_d[_password2]', '$enc_pass', '$ewallet_enc_password', '$post_d[country]', '$status', 'y', '$datetime', '$datetime')";

		if(!mysql_query($sql)){


			$errmsg.=__("We have encountered some error and the registration process has been failed.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");


		}else{
			
			$new_uid=mysql_insert_id();
			$array_matrix_upline[0] = $new_uid;
			$matrix_upline = $new_uid;				

			if($post_s['payment_channel'] == 'mwallet'){
				$mwallet = @mysql_result(mysql_query("select mwallet from {$vars["dbi"]["prefix"]}users where id='$uid' limit 1"), 0);
				$eswallet = @mysql_result(mysql_query("select eswallet from {$vars["dbi"]["prefix"]}users where id='$uid' limit 1"), 0);
				
				if($mwallet >= ($deduct_amount/2)){
					$mwallet_deduct = $eswallet_deduct = $deduct_amount/2;
				}else{
					$mwallet_deduct = $mwallet;
					$eswallet_deduct = $deduct_amount - $mwallet_deduct;
				}
				
				
				if(!mysql_query("update $db->users set eswallet=eswallet-$eswallet_deduct,mwallet=mwallet-$mwallet_deduct where id='$uid' limit 1")){
				
					$critical_error.="Error occur while member id#".$r_user['code']." register a new member id#$dist_code, the user #$uid {$vars[$post_s['payment_channel'].'_title']} could not be deducted with ".number_format($deduct_amount, 2)." for activation cost.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
		
				}else{
						
					$mwallet_descr = mysql_real_escape_string("Debited $vars[currency]".number_format($mwallet_deduct, 2)." for registering new member with ID#$dist_code for package {$r_package_d[$post_s['package']]}.");
					$eswallet_descr = mysql_real_escape_string("Debited $vars[currency]".number_format($eswallet_deduct, 2)." for registering new member with ID#$dist_code for package {$r_package_d[$post_s['package']]}.");
					
					if($mwallet_deduct>0){
						if(!mysql_query($sql="insert into ".$vars["dbi"]["prefix"]."member_mwallet_record (uid, type, amount, descr, cdate) values ('$uid', 'd', '$mwallet_deduct', '$mwallet_descr', '$datetime')")){
						
							$critical_error.="Error occur while member id#".$r_user['code']." register a new member id#$dist_code, the user #$uid {$vars[$post_s['payment_channel'].'_title']} has been deducted with ".number_format($deduct_amount, 2)." but the transaction history could not be recorded.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
						
						}else{
						
							$new_eid = mysql_insert_id();
		
							$last_bal = @mysql_result(mysql_query("select bal from {$vars["dbi"]["prefix"]}member_mwallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
		
							if(!$last_bal){
								
								$last_bal = 0;
								
							}
			
							$last_bal -= $mwallet_deduct;	
		
							@mysql_query("update {$vars["dbi"]["prefix"]}member_mwallet_record set bal='$last_bal' where id='$new_eid' limit 1");
								
						}
					}
					
					if(!mysql_query($sql="insert into ".$vars["dbi"]["prefix"]."member_eswallet_record (uid, type, amount, descr, cdate) values ('$uid', 'd', '$eswallet_deduct', '$eswallet_descr', '$datetime')")){
						
						$critical_error.="Error occur while member id#".$r_user['code']." register a new member id#$dist_code, the user #$uid {$vars[$post_s['payment_channel'].'_title']} has been deducted with ".number_format($deduct_amount, 2)." but the transaction history could not be recorded.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
					
					}else{
					
						$new_eid = mysql_insert_id();
	
						$last_bal = @mysql_result(mysql_query("select bal from {$vars["dbi"]["prefix"]}member_eswallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
	
						if(!$last_bal){
							
							$last_bal = 0;
							
						}
		
						$last_bal -= $eswallet_deduct;	
	
						@mysql_query("update {$vars["dbi"]["prefix"]}member_eswallet_record set bal='$last_bal' where id='$new_eid' limit 1");
							
					}
				}
			}else{
				if(!mysql_query("update $db->users set $post_s[payment_channel]=$post_s[payment_channel]-$deduct_amount where id='$uid' limit 1")){
				
					$critical_error.="Error occur while member id#".$r_user['code']." register a new member id#$dist_code, the user #$uid {$vars[$post_s['payment_channel'].'_title']} could not be deducted with ".number_format($deduct_amount, 2)." for activation cost.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
	
				}else{
					
					$wallet_descr = mysql_real_escape_string("Debited $vars[currency]".number_format($deduct_amount, 2)." for registering new member with ID#$dist_code for package {$r_package_d[$post_s['package']]}.");
	
					if(!mysql_query($sql="insert into ".$vars["dbi"]["prefix"]."member_$post_s[payment_channel]_record (uid, type, amount, descr, cdate) values ('$uid', 'd', '$deduct_amount', '$wallet_descr', '$datetime')")){
	
						$critical_error.="Error occur while member id#".$r_user['code']." register a new member id#$dist_code, the user #$uid {$vars[$post_s['payment_channel'].'_title']} has been deducted with ".number_format($deduct_amount, 2)." but the transaction history could not be recorded.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
	
					}else{
	
						$new_eid = mysql_insert_id();
	
						$last_bal = @mysql_result(mysql_query("select bal from {$vars["dbi"]["prefix"]}member_$post_s[payment_channel]_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
	
						if(!$last_bal){
	
							$last_bal = 0;
	
						}
	
						$last_bal -= $deduct_amount;
	
						@mysql_query("update {$vars["dbi"]["prefix"]}member_$post_s[payment_channel]_record set bal='$last_bal' where id='$new_eid' limit 1");
	
					}
	
				}	
			}
			


			//insert purchase record


			$first_sale = true;
			$total_bv = $total_dp = $total_rp = $vars['package'][$post_s['package']]['bv'];
			$price = $vars['package'][$post_s['package']]['price'];	
			$incentive_amount = $vars['package'][$post_s['package']]['incentive'];		
			$voucher_amount = $incentive_amount*240;		
			$total_bonus = $price * 2;
			$payment_channel = $post_s['payment_channel'];
			
			if($payment_channel=='twallet' || $payment_channel=='fwallet')
				$no_bv = 'y';
			else 
				$no_bv = 'n';
				
			if($payment_channel=='ewallet' || $payment_channel=='eswallet' || $payment_channel=='mwallet'){
				$collected = 'y';
				$collected_date = date('Y-m-d H:i:s');
				$incentive_date = date("Y-m-d", mktime(0, 0, 0, date('m'), date('d')+30, date('Y')));				
			}else{
				$collected = 'n';
				$collected_date = '0000-00-00 00:00:00';
				$incentive_date = '0000-00-00';
			}
			
			mysql_query("update $db->users set dividend_count=0,dividend_amount='".$incentive_amount."' where id=".$new_uid);
			
			
			if(!mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='".$r_package_d[$post_s['package']]."',counter='0',amount='".$incentive_amount."',total_bonus='".$total_bonus."',cdate='".date('Y-m-d')."'")){
				$errmsg.=__("We have encountered some error when insert incentive record.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
			}elseif(date('Y-m-d')<='2014-11-30'){
				switch($total_bv){
					case 3000:
						mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='GBP1000 Copper',counter='-1',amount='6.00',total_bonus='2000',cdate='".date('Y-m-d')."'");
						break;
					case 5000:
						mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='GBP3000 Bronze',counter='-1',amount='25.00',total_bonus='6000',cdate='".date('Y-m-d')."'");
						break;
					case 10000:
						mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='GBP5000 White Gold',counter='-1',amount='41.66',total_bonus='10000',cdate='".date('Y-m-d')."'");
						break;	
					case 30000:
						mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='GBP5000 White Gold',counter='-1',amount='41.66',total_bonus='10000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='GBP5000 White Gold',counter='-1',amount='41.66',total_bonus='10000',cdate='".date('Y-m-d')."'");
						break;	
					case 50000:
						mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						break;	
					case 100000:
						mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$new_uid',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						break;	
				}
			}
			
			//for those special case, get register point but no bonus payout
			$refund_bv = @mysql_result(mysql_query("select refund_bv from $db->users where id='$uid'"), 0) or 0;
			if($refund_bv>0 && $payment_channel=='eswallet'){
				mysql_query("update $db->users set dividend_count=0, owallet='$total_bv' where id='$new_uid'");
				
				mysql_query("update $db->users set refund_bv=refund_bv-".$total_bv." where id='$uid'");
				$total_bv = 0;	
				$share_price = 0;			
			}

			$sale_refno = $refno = "S" . rand(10000000,99999990);

			if(!mysql_query($sql="insert into $db->purchase (refno, creator, cid, uid, stockist_sale, member_sale, no_bv, amount, total_bv, total_dp, total_rp, payment_type, first_sale, collected, rank_a, status, cdate, edate) values ('$sale_refno', 'u', '$uid', '$new_uid', 'n', 'y', '$no_bv', '$cost', '$total_bv', '$total_dp', '$total_rp', '$payment_channel', 'y', 'n', '$rank_a', 'confirmed', '$datetime', '$datetime')")){


				$critical_error.="Error creating the member purchase record when member ID #$uid register another member id#$new_uid. Please manually execute the SQL below to record the transaction:\n\n$sql\n\nError: ".mysql_error()."\n";


				$pid="0";


			}else{

				$pid=mysql_insert_id();


				//insert sales detail


				$purchased_prods[$post_s['package']] = 1;

				foreach($purchased_prods as $refno => $qty){


					$this_cost=$cost;


					$this_bv=$total_bv;


					if(!mysql_query($sql="insert into $db->purchase_detail (slid, refno, title, prod_type, qty, amount, bv, dp, rp, total, total_bv) values ('$pid', '".AddSlashes($refno)."', '".AddSlashes($r_package_d[$refno])."', 'n', '$qty', '$cost', '$total_bv', '$total_dp', '$total_rp', '$this_cost', '$this_bv')")){


						$critical_error.="Error creating the member sales detail when member ID #$uid register another member id#$new_uid. Please manually execute the SQL below to record the sales detail.\n\nSQL: $sql\n\nError: ".mysql_error()."\n\n";


					}


				}


			}

			

			$activation_link="<a href='".M_URL."/$activation_file?vc=$vc&email=$post_s[_email]'>".M_URL."/$activation_file?vc=$vc&email=$post_s[_email]</a>";


			//email user


			$msg_style=$vars["css"]["msg_style"];


			$td_style=$vars["css"]["td_style"];


			$td_title_style=$vars["css"]["td_title_style"];


			$u_sub="$vars[title] - Thank You for Your Registration";

			$user_info=get_user_detail_by_id($new_uid);
			
			$user_table="


			<table align='center' ".$vars["css"]["table_style"]." width='100%'>


				<tr>


					<td $td_title_style colspan='2'>".__("Account Information")."</td>


				</tr>


				<tr>


					<td $td_style>".__("Sponsor")."</td>


					<td $td_style>".($ref_id? $post_s['ref'] : "None")."</td>


				</tr>


				<tr>


					<td $td_style>".__("Placement ID")."</td>


					<td $td_style>".($matrix_upline_id? $post_s['matrix_upline'] : "None")."</td>


				</tr>


				<tr>


					<td $td_style>".__("Package")."</td>


					<td $td_style>{$r_package_d[$post_s['package']]} (".__("Daily Dividend")." - {$vars['package'][$post_s['package']]['incentive']})</td>


				</tr>


				<tr>


					<td $td_style>".__("Member ID")."</td>


					<td $td_style>$user_info[code]</td>


				</tr>


				<tr>


					<td $td_style>".__("Password")."</td>


					<td $td_style>$post_s[_password]</td>


				</tr>


				<tr>


					<td $td_style>".__("AuthCode")."</td>


					<td $td_style>$post_s[_password2]</td>


				</tr>



				<tr>


					<td $td_style>".__("Email")."</td>


					<td $td_style>$post_s[_email]</td>


				</tr>


				<tr>


					<td $td_style>".__("Country")."</td>


					<td $td_style>".$country_code_d[$post_s["country"]]."</td>


				</tr>


			</table>";


			$u_msg=


			"<p $msg_style>Dear $post_s[_name], <br />\n<br />\nThank you for your registration. The user information for your new account is listed below:</p>


			$user_table";


			if(email_user($post_s["_email"], $user_info['code'], $u_sub, $u_msg)){


				$email_msg=replace_tag(__("A welcome email has been sent to '<%email%>'."), array("<%email%>"=>$post_h['_email']));


			}else{


				$email_errmsg=replace_tag(__("The Welcome email could not be sent to '<%email%>', please contact us for more information."), array("<%email%>"=>$post_h['_email']));


			}




		}


		if(!$errmsg){
			/*
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, "http://".$_SERVER['HTTP_HOST']."/cron/rebuild_tree.php");
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_TIMEOUT, 5);
			curl_exec($ch);
			curl_close($ch);
			*/
			
			rebuild(1);
			rebuild2(1);
			
			$_SESSION["user_register"]=false;


			//$msg=__("Thank you for your registration.")." ".($email_msg? $email_msg : "<span class='red'>$email_errmsg</span>")."<br />\n";
			$msg=__("Thank you for your registration.");


			print format_member_page(str_replace("<%tab_content%>", "<h2>$page_title</h2>".format_msg($msg)."<p>".__("The user information of your account is listed below:")."</p>$user_table", $tab), $this_title, $content_title, $css);


			exit();


		}


	}





	$errmsg=$errmsg? format_err($errmsg) : "";


	


	if($critical_error){echo $critical_error;


		$a_sub = "$vars[title] - User Registration Error";


		$a_msg = 


		"<p>Dear admin,</p>


		<p>Error occur while member id#$uid register a new member, error below:</p>


		$critical_error";


		email_admin($a_sub, $a_msg, 'e');


	}


}


$_SESSION["user_register"]=true;





$form_fields=array("ref"=>$r_user['code'],"matrix_upline"=>$r_user['code'],"matrix_position"=>"","payment_channel"=>"ewallet","package"=>"","_username"=>"","_password"=>"","password2"=>"","_email"=>"","country"=>"CN");


foreach($form_fields as $field => $default){


	$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;


	$dis[$field]=!$posting? $default : $post_h[$field];


}


if($get_s["pos"]){
	$dis['matrix_position'] = $get_s["pos"];
}

if($get_s["upline"]){
	$dis['matrix_upline'] = $get_s["upline"];
}


$position_select=build_select($r_position, $r_position_d, $dis['matrix_position'], 'matrix_position', $inputbox_style);


$country_select=build_select($country_code, $country_code_d, $dis["country"], "country", $inputbox_style);


$payment_channel_select=build_select($r_payment_channel, $r_payment_channel_d, $dis['payment_channel'], 'payment_channel', $inputbox_style);


$package_select=build_select($r_package, $r_package_d, $dis['package'], 'package', "style='width:100%;'");




//referrer


if($dis["ref"]){


	if($r=get_user_detail_by_code($dis["ref"])){


		$ref_text="<span class='bold'>".replace_tag(__("Sponsor ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$r["code"], "<%name%>"=>$r["name"]))."</span>";


	}else{


		$ref_text="<span class='red'>".__("Invalid Sponsor")."</span>";


	}


}


if($dis["matrix_upline"]){


	if($r=get_user_detail_by_code($dis["matrix_upline"])){


		$up_text="<span class='bold'>".replace_tag(__("Placement ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$r["code"], "<%name%>"=>$r["username"]))."</span>";


	}else{


		$up_text="<span class='red'>".__("Invalid Upline")."</span>";


	}


}





//javascript


$jvscript=


"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("common.js,jquery.js")."'></script>


<script type='text/javascript'>


jQuery(document).ready(function(j){


 j('form[@name=member_form],form[@name=member_form2]').submit(function(){


  j('input[@name=submit_btn]').attr('disabled','disabled');


 });





 j('input#check_ref_btn').click(function(){


  j('span#ref_text').html('').removeClass('red');


  if(j('input[@name=ref]').val()==''){


   j('span#ref_text').html('".AddSlashes(__("Please provide a Sponsor ID!"))."').addClass('red');


  }else{


   j('span#ref_text').html('Checking...');


   j(this).attr('disabled','disabled');


   j.ajax({


    url: '$this_file?aj=1&check_ref=1',


    data: {'ref': j('input[@name=ref]').val()},


    type: 'post',


    dataType: 'xml',


    error: function(){


     j('span#ref_text').html('".AddSlashes(__("Error checking..."))."').addClass('red');


    },


    success: function(data){


     var mesg='';


     if(j('loggedout', data).text()=='loggedout'){


      mesg='".AddSlashes(__("You have been logged out."))."';


     }else{


      j(data).find('msg').each(function(){


       mesg+=j(this).text()+' ';


      });


     }


     var status=j(data).find('status').text();


     j('span#ref_text').html(mesg).addClass(status==1? 'bold' : 'red');


    },


    complete: function(){


     j('input#check_ref_btn').attr('disabled','');


    }


   });


  }


 });


 


 j('input#check_up_btn').click(function(){


  j('span#up_text').html('').removeClass('red');


  if(j('input[@name=matrix_upline]').val()==''){


   j('span#up_text').html('".AddSlashes(__("Please provide a Placement ID!"))."').addClass('red');


  }else{


   j('span#up_text').html('Checking...');


   j(this).attr('disabled','disabled');


   j.ajax({


    url: '$this_file?aj=1&check_upline=1',


    data: {'ref': j('input[@name=matrix_upline]').val()},


    type: 'post',


    dataType: 'xml',


    error: function(){


     j('span#up_text').html('".AddSlashes(__("Error checking..."))."').addClass('red');


    },


    success: function(data){


     var mesg='';


     if(j('loggedout', data).text()=='loggedout'){


      mesg='".AddSlashes(__("You have been logged out."))."';


     }else{


      j(data).find('msg').each(function(){


       mesg+=j(this).text()+' ';


      });


     }


     var status=j(data).find('status').text();


     j('span#up_text').html(mesg).addClass(status==1? 'bold' : 'red');


    },


    complete: function(){


     j('input#check_up_btn').attr('disabled','');


    }


   });


  }


 });


});







function goback(){


	q('__edit').value = 1;


	q('__confirm').value = '';


	document.member_form2.submit();


}



</script>";







$display_fields=array("ref","matrix_upline","_username","_password","_password2","_email");


foreach($form_fields as $field => $default){


	if(in_array($field, $display_fields)){


		$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;


		$dbr=explode("#", $vars["dbr"]["users"][$db_fieldname]);


		$readonly=$textarea=$password=false;
	
		$extra_display='';


		if(in_array($field, array("_password","_password2"))){


			$password=true;


		}


		$readonly_str=$readonly? "readonly='readonly'" : "";


		$form_inputfield[$db_fieldname]="


		<tr id='input_$db_fieldname'>


			<td width='$td_width'><div style='width:".$td_width."px;'>".__($dbr[4]).__(":")."</div></td>


			<td>".($preview? ($dis[$field]? $dis[$field] : '&nbsp;') : ($textarea? "<textarea name='$field' rows='6' $inputbox_style $readonly_str>".$dis[$field]."</textarea>" : "


			<input type='".($password? "password" : "text")."' name='$field' $inputbox_style value=\"".$dis[$field]."\" $readonly_str />"))."$extra_display</td>


		</tr>";


	}


}





//##### PREVIEW #####


if($preview){


	foreach($post_h as $f=>$v){


		$hidden_fields.="<input type='hidden' name=\"$f\" value=\"$v\" />\n";


	}


	$register="


	<form name='member_form2' method='post' action='$this_file'>


	<input type='hidden' name='__req' value='1' />


	<input type='hidden' name='__edit' />


	<input type='hidden' name='__confirm' value='1' />


	$hidden_fields


	<br>


	<table class='pbt_table rev'>


		$form_inputfield[ref]


		$form_inputfield[matrix_upline]


		<tr>


			<td>".__("Position").__(":")."</td>


			<td>".($dis['matrix_position']=="1"? __('Left') : __('Right'))."</td>


		</tr>


		<tr>


			<td>".__("Package").__(":")."</td>


			<td>{$r_package_d[$dis['package']]} (".__("Daily Dividend")." - {$vars['package'][$dis['package']]['incentive']})</td>


		</tr>


		<tr>


			<td>".__("Payment Channel").__(":")."</td>


			<td>{$r_payment_channel_d[$dis['payment_channel']]}</td>


		</tr>


		$form_inputfield[email]

		<tr>


			<td>".__("Country").__(":")."</td>


			<td>{$country_code_d[$dis['country']]}</td>


		</tr>


	</table>


	<table class='pbt_table'>


		<tr>


			<td colspan='2' class='center' style='padding:20px 0 20px 0;'>


			<input type='button' name='back_btn' value=\"".__("Back")."\" onclick=\"goback();\" />


			<input type='submit' name='submit_btn' value=\"".__("Register")."\" />


			</td>


		</tr>


	</table>";


	//##### FIRST TIME #####


}else{


	$register=($errmsg?


	"$errmsg" : "")."


	<form name='aj_form' method='post' action='$this_file'></form>


	<form name='member_form' method='post' action='$this_file'>


	<input type='hidden' name='__req' value='1' />

	<br>
		
	<table class='pbt_table'>



		$form_inputfield[ref]


		$form_inputfield[matrix_upline]


		<tr>


			<td>".__("Position").__(":")."</td>


			<td>$position_select</td>


		</tr>


		<tr>


			<td>".__("Activation Package").__(":")."</td>


			<td>$package_select</td>


		</tr>


		<tr>


			<td>".__("Payment").__(":")."</td>


			<td>$payment_channel_select</td>


		</tr>


		$form_inputfield[password]


		<tr>


			<td>".__("AuthCode").__(":")."</td>


			<td><input type='password' name='_password2' $inputbox_style value=\"$dis[password2]\"></td>


		</tr>


		$form_inputfield[name]


		$form_inputfield[email]


		<tr>


			<td>".__("Country").__(":")."</td>


			<td>$country_select</td>


		</tr>


		<tr>


			<td colspan='2' class='center' style='padding:20px 0 20px 0;'>


			<input type='submit' name='submit_btn' value=\"".__("Next")."\" />


			</td>


		</tr>


	</table>";


}





$css.="


<style type='text/css'>


td{


	font-size:12px;


}





table.rev td{


	border:1px solid #000;


}


</style>";





$content="<h2>$page_title</h2>$register";


$content=str_replace("<%tab_content%>", $content, $tab);



print format_member_page($content, $this_title, $content_title, $css.$jvscript);

?>